<template>
  <div class="add-movie-container">
    <h1 class="title">{{ isEditing ? '编辑商品' : '添加商品' }}</h1>
    
    <form class="add-movie-form" @submit.prevent="submitForm">
      <div class="form-group">
        <label for="title">商品标题</label>
        <input 
          type="text" 
          id="title" 
          v-model="movieData.title" 
          required
        />
        <p class="error" v-if="errors.title">{{ errors.title }}</p>
      </div>
      
      <div class="form-group">
        <label for="description">描述</label>
        <textarea 
          id="description" 
          v-model="movieData.description" 
          rows="4"
          required
        ></textarea>
        <p class="error" v-if="errors.description">{{ errors.description }}</p>
      </div>
      
      <div class="form-group">
        <label for="director">导演</label>
        <input 
          type="text" 
          id="director" 
          v-model="movieData.director" 
          required
        />
        <p class="error" v-if="errors.director">{{ errors.director }}</p>
      </div>
      
      <div class="form-group">
        <label for="releaseDate">上映日期</label>
        <input 
          type="date" 
          id="releaseDate" 
          v-model="movieData.releaseDate" 
          required
        />
        <p class="error" v-if="errors.releaseDate">{{ errors.releaseDate }}</p>
      </div>
      
      <div class="form-group">
        <label for="category">分类</label>
        <select 
          id="category" 
          v-model="movieData.categoryId"
          required
        >
          <option value="">请选择分类</option>
          <option v-for="category in categories" :key="category.id" :value="category.id">
            {{ category.name }}
          </option>
        </select>
        <p class="error" v-if="errors.categoryId">{{ errors.categoryId }}</p>
      </div>
      
      <div class="form-group">
        <label for="poster">海报 URL</label>
        <input 
          type="text" 
          id="poster" 
          v-model="movieData.posterUrl" 
        />
      </div>
      
      <div class="form-group">
        <label for="rating">评分</label>
        <input 
          type="number" 
          id="rating" 
          v-model="movieData.rating" 
          min="0" 
          max="10" 
          step="0.1"
          required
        />
        <p class="error" v-if="errors.rating">{{ errors.rating }}</p>
      </div>
      
      <div class="form-actions">
        <button type="submit" class="submit-btn">{{ isEditing ? '更新商品' : '添加商品' }}</button>
        <button type="button" class="cancel-btn" @click="cancel">取消</button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useMovieStore } from '@/stores/movie';
import { useCategoryStore } from '@/stores/category';
import { useRoute, useRouter } from 'vue-router';

const movieStore = useMovieStore();
const categoryStore = useCategoryStore();
const route = useRoute();
const router = useRouter();

const isEditing = ref(false);
const movieData = ref({
  title: '',
  description: '',
  director: '',
  releaseDate: '',
  categoryId: '',
  posterUrl: '',
  rating: 0
});
const categories = ref([]);
const errors = ref({});
const loading = ref(false);

const fetchCategories = async () => {
  try {
    categories.value = await categoryStore.fetchCategories();
  } catch (error) {
    console.error('获取分类失败:', error);
  }
};

const fetchMovie = async () => {
  if (route.params.id) {
    try {
      const movie = await movieStore.getMovie(route.params.id);
      movieData.value = {
        title: movie.title,
        description: movie.description,
        director: movie.director || '',
        releaseDate: movie.releaseDate || '',
        categoryId: movie.categoryId || '',
        posterUrl: movie.posterUrl || '',
        rating: movie.rating || 0
      };
      isEditing.value = true;
    } catch (error) {
      console.error('获取商品失败:', error);
      router.push('/');
    }
  }
};

const validateForm = () => {
  errors.value = {};
  if (!movieData.value.title) errors.value.title = '标题不能为空';
  if (!movieData.value.description) errors.value.description = '描述不能为空';
  if (!movieData.value.director) errors.value.director = '导演不能为空';
  if (!movieData.value.releaseDate) errors.value.releaseDate = '上映日期不能为空';
  if (!movieData.value.categoryId) errors.value.categoryId = '请选择分类';
  if (movieData.value.rating === undefined || movieData.value.rating < 0 || movieData.value.rating > 10) 
    errors.value.rating = '评分需在0-10之间';
  return Object.keys(errors.value).length === 0;
};

const submitForm = async () => {
  if (!validateForm()) return;
  
  loading.value = true;
  try {
    let response;
    if (isEditing.value) {
      response = await movieStore.updateMovie(route.params.id, movieData.value);
    } else {
      response = await movieStore.addMovie(movieData.value);
    }
    router.push(`/movie/${response.id}`);
  } catch (error) {
    console.error('操作失败:', error);
  } finally {
    loading.value = false;
  }
};

const cancel = () => {
  router.push('/');
};

onMounted(async () => {
  await fetchCategories();
  if (route.params.id) await fetchMovie();
});

watch(
  () => route.params.id,
  fetchMovie
);
</script>

<style scoped>
/* 保持原有样式并添加错误提示样式 */
.add-movie-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.add-movie-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  font-weight: bold;
  margin-bottom: 5px;
}

.form-group input,
.form-group textarea,
.form-group select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-group .error {
  color: #e94560;
  font-size: 12px;
  margin-top: 3px;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.submit-btn {
  flex: 1;
  padding: 10px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  flex: 1;
  padding: 10px;
  background-color: #f0f2f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}
</style>